﻿using System;
using System.Collections.Generic;
using System.Net;

using Thrift.Transport;
using Thrift.Protocol;

using Apache.Cassandra;
using Client = Apache.Cassandra.Cassandra.Client;

using RexToy.DesignPattern;
using RexToy.Cassandra.Meta;

namespace RexToy.Cassandra
{
    public sealed class Connection : DisposableBase, IConnection
    {
        private Cluster _cluster;
        private RawConnection _raw;
        private string _keyspace;
        public Connection(Cluster cluster, string keyspace)
        {
            cluster.ThrowIfNullArgument("cluster");
            keyspace.ThrowIfNullArgument("keyspace");

            _cluster = cluster;
            _keyspace = keyspace;
            _raw = _cluster.GetRawConnection();
        }

        public DnsEndPoint EndPoint
        {
            get { return _raw.EndPoint; }
        }

        internal Client Client
        {
            get { return _raw.Client; }
        }

        public void Open()
        {
            _raw.Open();
            _raw.Client.set_keyspace(_keyspace);
        }

        public void Close()
        {
            _raw.Close();
            _keyspace = string.Empty;
        }

        protected override void DisposeManagedObject()
        {
            _cluster.PutRawConnection(_raw);
        }
    }
}
